<template>
  <el-dialog class :title="title" :visible.sync="dialogVisible" :close-on-click-modal="false" width="80%"
    @close="close">
    <el-tabs type="border-card" v-model="actived" @tab-click="tabChange">
      <el-tab-pane :label="tab.name" :name="tab.name" v-for="(tab, index) in gameList" :key="tab.id" :disabled="isEdit"
        v-loading="loading">
        <div class="form-box" v-if="actived == tab.name">
          <el-form :ref="'form' + index" :model="form" :inline="true" :rules="rules" label-width="100px"
            class="demo-ruleForm">
            <el-form-item label="商品标题" prop="title" class="">
              <el-input v-model="form.title" placeholder="请输入" style="width: 600px;" maxlength="200" show-word-limit/>
            </el-form-item><br />
            <el-form-item label="出售价格" prop="price">
              <el-input v-model="form.price" placeholder="请输入价格" />
            </el-form-item><br v-if="form.gameName != '和平精英'"/>
            <!-- 王者荣耀个性化属性 start -->
            <el-form-item prop="f17" v-if="form.gameName == '王者荣耀'" label="营地ID" class="attr-input-content">
              <div class="input-btn">
                <el-input v-model="form.f17" color="#333" placeholder="请输入营地ID加载数据"
                  @keyup.enter.native="getRoleList"></el-input>
                <el-button type="primary" size="mini" plain @click="getRoleList" style="margin-left:20px"
                  :loading="btnLoading">加载数据</el-button>
              </div>
            </el-form-item>
            <br v-if="form.gameName == '王者荣耀'" />
            <el-form-item prop="roleId" v-if="form.gameName == '王者荣耀'" label="角色列表" class="attr-input-content">
              <div class="input-btn">
                <el-select v-model="form.roleId" placeholder @change="roleSelect">
                  <el-option v-for="item2 in roleList" :key="item2.zdytext" :label="item2.zdytext"
                    :value="item2.roleId"></el-option>
                </el-select>
              </div>
            </el-form-item>
            <br v-if="form.gameName == '王者荣耀'" />
            <!-- 王者荣耀个性化属性 end -->
            <!-- 和平精英个性化属性 start -->
            <el-form-item prop="f13" v-if="form.gameName == '和平精英'" label="营地ID" class="attr-input-content">
              <div class="input-btn">
                <el-input v-model="form.f13" color="#333" placeholder="请输入营地ID"
                  @keyup.enter.native="getQRcode"></el-input>
                <el-button type="primary" size="mini" plain @click="getQRcode" style="margin-left:20px"
                  :loading="btnLoading">授权</el-button>
              </div>
            </el-form-item>
            <br v-if="form.gameName == '和平精英'" />
            <!-- 和平精英个性化属性 end -->
            <el-form-item label="系统" prop="systemId" v-if="form.gameType === 0">
              <el-select v-model="form.systemId" filterable placeholder="请选择" @change="sysChange">
                <el-option v-for="dict in sysList" :key="dict.id" :label="dict.fieldName" :value="dict.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="运营商" prop="carrierId" v-if="form.gameType === 0">
              <el-select v-model="form.carrierId" filterable placeholder="请选择" @change="getAreaList">
                <el-option v-for="dict in carrierList" :key="dict.id" :label="dict.fieldName" :value="dict.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="大区" prop="groupId">
              <el-select v-model="form.groupId" filterable placeholder="请选择" @change="getServiceList">
                <el-option v-for="dict in areaList" :key="dict.id" :label="dict.fieldName" :value="dict.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="服务器" prop="serverId">
              <el-select v-model="form.serverId" filterable placeholder="请选择" @change="serverChange">
                <el-option v-for="dict in serverList" :key="dict.id" :label="dict.fieldName" :value="dict.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="自编号" prop="thirdId">
              <el-input v-model="form.thirdId" placeholder="请填写自编号" />
            </el-form-item>
            <el-form-item label="账号" prop="accountNumber">
              <el-input v-model="form.accountNumber" placeholder="请输入账号" />
            </el-form-item>
            <el-form-item label="密码" prop="accountPassword">
              <el-input v-model="form.accountPassword" placeholder="请输入密码" />
            </el-form-item><br />
            <el-form-item label="绑定手机" prop="telid">
              <span>
                <span v-if="selectedPhone" style="margin-right: 5px;">{{ selectedPhone }}</span>
                <el-button size="small" plain type="primary" @click="openSelectPhone">选择手机</el-button>

              </span>
            </el-form-item>

            <el-form-item label="手机号" prop="securityPhone">
              <el-input v-model="form.securityPhone" placeholder="请输入绑定手机号" maxlength="11"/>
            </el-form-item>


            <!-- <el-form-item label="成本价格" prop="costPrice">
              <el-input v-model="form.costPrice" placeholder="请输入成本价格" />
            </el-form-item> -->

            <el-row>
              <el-form-item label="商品描述" prop="des">
                <el-input v-model="form.des" type="textarea" placeholder="请按顺序编写简介信息内容，例如：王者荣耀 安卓Q 有二次 英雄数量 皮肤数量 皮肤简介..."
                  :rows="8" style="width:700px" maxlength="1500" show-word-limit/>
                <el-button type="primary" plain @click="zidongChange" size="mini">自动识别</el-button>
              </el-form-item>
            </el-row>
            <!-- 渲染自定义字段 -->
            <div v-if="attrs && attrs.length">
              <span v-for="custom in attrs" :key="custom.id">
                <div v-if="custom.fieldType == 'checkbox'"></div>
                <el-form-item :label="custom.fieldName" :prop="custom.aavName" v-if="custom.isEnable === '0'">

                  <el-input v-model="form[custom.aavName]" :placeholder="`请填写${custom.fieldName}`"
                    v-if="custom.fieldType == 'input'" />
                  <el-input-number v-model="form[custom.aavName]" :step="0.1" :max="99999" :controls="false"
                    style="text-align: left;" :placeholder="`请填写${custom.fieldName}`"
                    v-if="custom.fieldType == 'number'"></el-input-number>
                  <el-date-picker v-model="form[custom.aavName]" type="datetime" :placeholder="`请选择${custom.fieldName}`"
                    value-format="yyyy-MM-dd hh:mm:ss" v-if="custom.fieldType == 'date'">
                  </el-date-picker>
                  <!-- <el-input v-model="form[custom.aavName]" v-show="false"></el-input> -->
                  <el-checkbox-group v-model="form[custom.aavName + 'rander']" v-if="custom.fieldType == 'checkbox'"
                    @change="checkboxChange($event, custom.aavName)">
                    <el-checkbox :label="checkItem.id" v-for="checkItem in custom.childAttributes" :value="checkItem.id"
                      :key="checkItem.id">{{ checkItem.fieldName }}</el-checkbox>
                  </el-checkbox-group>


                  <el-select v-model="form[custom.aavName]" placeholder="请选择" v-if="custom.fieldType == 'radio'">
                    <el-option v-for="item in custom.childAttributes" :key="item.id" :label="item.fieldName"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
                <div v-if="custom.fieldType == 'checkbox'"></div>
              </span>
            </div>
            <!-- <el-row>
              <el-form-item label="重要信息备注" prop="sinNum">
                <el-input v-model="form.sinNum" type="textarea" placeholder="可备注回收渠道，包赔信息，卖家信息等其他重要信息。" :rows="4"
                  style="width:700px" />
              </el-form-item>
            </el-row> -->

            <el-row>
              <el-form-item label="视频" prop>
                <el-upload class="upload-demo" :action="uploadImgUrl" :on-remove="handleVideoRemove"
                  :on-success="handleVideoSuccess" multiple :limit="1" accept="mp4" :file-list="videoList">
                  <el-button size="small" type="primary">点击上传</el-button>
                </el-upload>
              </el-form-item>
            </el-row>
            <el-row :class="{ 'hiddenupload': titleImgList.length }">
              <el-form-item label="商品首图" prop="">
                <div class="flex">
                  <el-input v-model="form.titleImg" v-show="false"></el-input>
                  <el-upload class :action="uploadImgUrl" :file-list="titleImgList" :show-file-list="true"
                    list-type="picture-card" :limit="1" :on-success="handleAvatarSuccess" :on-remove="handleAvatarRemove"
                    :on-preview="handlePictureCardPreview">
                    <i class="el-icon-plus"></i>
                  </el-upload>
                  <el-button plain style="height: 35px;margin-left: 10px;" type="primary" @click="openGetInfoDialog"
                    :loading="makeTitleImgBtnLoading">
                    首图生成</el-button>
                </div>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="详情图片" prop>
                <div class="flex">
                  <el-upload :action="uploadImgUrl" :file-list="imgShowList" list-type="picture-card"
                    :on-preview="handlePictureCardPreview" :on-exceed="uploadNumber" :multiple="true" :drag="true"
                    :on-success="handleUploadSuccess" :limit="50" :on-remove="handleRemove" :http-request="uploadImgs">
                    <i class="el-icon-plus"></i>
                  </el-upload>
                  <el-button plain style="height: 35px;margin-left: 10px;" type="primary" @click="getDetailImgs"
                    :loading="makeDetailImgBtnLoading">
                    详情图生成</el-button>
                </div>

              </el-form-item>
            </el-row>

            <div class="center">
              <el-button @click="close()">取消</el-button>
              <el-button type="primary" @click="submitForm('form' + index)" :loading="loading">提交</el-button>
            </div>
          </el-form>
        </div>
      </el-tab-pane>
    </el-tabs>
    <!-- 展示和平营地授权二维码 -->
    <el-dialog title="营地授权" :visible.sync="roleVisible" width="310px" append-to-body>
      <iframe style="height: 350px;" :src="poxiaoHpQrcode" frameborder="0"></iframe>
      <div style="text-align: center;">
        <el-button type="primary" size="mini" plain @click="getHpInfo" style="margin-left:20px"
          :loading="btnLoading">我已授权</el-button>
      </div>

    </el-dialog>

    <!-- <GetInfoDialog ref="getInfoDialog" @autoGetSubmit="autoGetSubmit"></GetInfoDialog> -->
    <selectPhone ref="selectPhone" @change="getSelectPhone"></selectPhone>

  </el-dialog>
</template>

<script>
import { getDicts } from "@/api/system/dict/data";
import ImageCompressor from 'image-compressor.js'
import { postUpload } from "@/api/upload";
import phoneApi from '@/api/phoneManage';
// import GetInfoDialog from "../../autoProduction/dialog/getInfoDialog"
import selectPhone from "./selectPhone.vue"
import gameConfigApi from "../../../api/gameConfig";
import goodsListApi from "../../../api/gameConfig/goodsList";
import gameListApi from "@/api/gameConfig/gameList"
import gameDictionaryApi from "../../../api/gameConfig/gameDictionary";
import infoApi from "@/api/autoProduction/information.js";
import makeImgsV3 from "@/utils/makeImgs-v3";
export default {
  name: "pick",
  components: { selectPhone },
  data() {
    var validatePass = (rule, value, callback) => {
      if (!value) {
        callback();
      } else if (!/^1[3-9][0-9]\d{8}$/.test(value)) {
        callback(new Error('手机号不正确!'));
      } else {
        callback();
      }
    };
    return {
      title: "新增游戏账号",
      dialogVisible: false,
      btnLoading: false,
      makeTitleImgBtnLoading: false,
      makeDetailImgBtnLoading: false,
      loading: false,
      isEdit: false,
      isSCQ: false, //从生成器打开本弹窗
      wzry: false,
      roleVisible: false,
      poxiaoHpQrcode: '',
      actived: "王者荣耀",
      roleList: [],//王者荣耀角色列表
      gameList: [],
      // 表单参数
      form: {
        type: "",
        des: '',
        securityPhone: '',
        serverId: ''
      },
      selectedPhone: '',
      sysList: [],//系统列表
      carrierList: [],//运营商列表
      areaList: [],//大区列表
      serverList: [],//服务器列表

      //游戏大区
      regionalArr: [],
      levelArr: [],
      lableInput: null,
      lableType: null,
      imgFileList: [],
      imgShowList: [],
      titleImgList: [],
      videoList: [],
      ifSpecial: false,
      uploadImgUrl: "",
      customAttr: null,
      newImages: [],//编辑的时候新增加的图片，新增的时候新增加的图片
      attrs: [],
      rules: {
        title:[
        { required: true, message: "请输入商品标题", trigger: "blur" }
        ],
        regional: [
          { required: true, message: "请选择区服", trigger: "change" }
        ],
        level: [
          { required: true, message: "请选择实名认证", trigger: "change" }
        ],
        gameName: [
          { required: true, message: "请输入自编号", trigger: "blur" }
        ],
        extractAccount: [
          { required: true, message: "请输入账号", trigger: "blur" }
        ],
        price: [{ required: true, message: "请输入售价", trigger: "blur" }],
        des: [{ required: true, message: "请输入简介", trigger: "blur" }],
        accountNumber:[{required: true, message: "请输入账号", trigger: "blur"}],
        securityPhone: [{ validator: validatePass, trigger: 'blur' }]
        // level
      }
    };
  },
  created() {
    this.uploadImgUrl = process.env.VUE_APP_BASE_API + "/upload/image";

  },
  methods: {
    // 打开弹窗
    async open(flag, data) {
      this.reset();
      await this.getGameList()
      this.dialogVisible = true;
      if (flag == "edit") {
        this.title = "修改游戏账号";
        this.isEdit = true;
        this.handleUpdate(data);
      } else {
        this.title = "新增游戏账号";
        this.tabChange();
        this.isEdit = false;
        this.isSCQ = false;
      }
    },
    // 打开选择手机弹窗
    openSelectPhone() {
      this.$refs.selectPhone.open()
    },
    // 选择绑定手机
    getSelectPhone(item) {
      this.form.telid = item.id
      this.selectedPhone = item.type + '/' + (item.num ? item.num + '/' : '') + (item.tel ? item.tel : '')
      this.form.telnote = this.selectedPhone
      // if (!this.form.securityPhone) {
      //   this.form.securityPhone = item.type + '/' + (item.num ? item.num + '/' : '') + (item.tel ? item.tel : '')
      // }
    },
    // 游戏列表
    async getGameList() {
      let res = await gameListApi.getGameList()
      // console.log("%c Line:278 🍫 res", "color:#465975", res);
      this.gameList = res.rows
      if (res.rows && res.rows.length) {
        this.actived = res.rows[0].name
        this.form.gameId = res.rows[0].id
        this.form.gameType = res.rows[0].type
        this.form.gameName = res.rows[0].name
        this.getSysList()
        this.getYysList()
        if (res.rows[0].type == 1) {
          // 端游
          this.getAreaList()
        }
      }
    },
    // 游戏类型切换
    // tabs切换时触发
    tabChange() {
      this.reset();
      this.form.gameName = this.actived;
      if (this.gameList && this.gameList.length) {
        this.gameList.forEach(item => {
          // console.log("%c Line:231 🍿 item", "color:#42b983", item);
          if (item.name == this.actived) {
            this.form.gameId = item.id
            this.form.gameType = item.type
            if (item.type == 1) {
              // 端游
              this.getAreaList()
            } else {
              this.getSysList()
              this.getYysList()
            }
          }
        })
      }
      this.selectDialogGameType();
    },
    /**
     * 
     *  王者荣耀个性化营地获取 start
     */

    //获取角色列表 f17是营地ID
    getRoleList() {
      if (this.form.f17) {
        this.btnLoading = true;
        infoApi
          .getRoleList({
            campId: this.form.f17
          })
          .then(res => {
            if (res.data) {
              this.btnLoading = false;
              this.roleList = res.data;
              if (this.roleList.length) {
                //遍历添加展示数据
                this.roleList.forEach(item => {
                  item.zdytext = `${item.areaName}/${item.roleJob}/${item.roleName}`;
                });
                // this.formData.roleValue = this.roleList[0].zdytext;
                this.form.roleId = this.roleList[0].roleId;
                this.getRoleInfo(this.roleList[0].roleId);
              }
            }
          })
          .catch(err => {
            this.btnLoading = false;
          });
      } else {
        this.$alert("请先填写营地ID！");
      }
    },
    //角色选中
    roleSelect(e) {
      this.getRoleInfo(e);
    },
    //获取角色详情
    getRoleInfo(roleId) {
      if (roleId) {
        this.btnLoading = true;
        infoApi
          .getRoleInfo({
            campId: this.form.f17,
            roleId: roleId
          })
          .then(res => {
            this.btnLoading = false;
            this.showCheckbox(res)
          });
      } else {
        this.$alert("请先选择角色信息！");
      }
    },
    //  回显  拼装简介
    showCheckbox(res) {
      console.log("%c Line:436 🌰 res", "color:#e41a6a", res);
      let data = res.data
      let str = ''
      if (data.listJson && data.listJson.length) {
        data.listJson.forEach(r => {
          str = str + r.szHeroTitle + '-' + r.szTitle + ' '
        })
      }
      this.form.f8 = data.skinMap.skinNum
      this.form.f7 = data.skinMap.heroNum
      this.form.f4 = data.skinMap.totalCount
      let str2 = `${data.skinMap.areaName}-贵族积分${data.skinMap.totalCount}-V${data.skinMap.vipLevel}-${data.skinMap.skinNum}皮肤-${data.skinMap.heroNum}英雄 `
      this.form.des = (this.form.des || '') + ' ' + str2 + str + ` 营地ID:${this.form.f17} `
      this.zidongChange()
    },
    /**
         * 
         *  王者荣耀个性化营地获取 end
         */
    /**
     * 
     *  和平精英个性化营地获取 start
     */

    //获取角色列表 f13是营地ID
    getQRcode() {
      if (!this.form.carrierId) {
        this.$alert("请先选择运营商！");
        return
      }
      if (this.form.f13) {
        this.btnLoading = true;
        infoApi
          .getHpQRcode({
            yingdi: this.form.f13,
            authType: this.form.carrierId == '38838' ? '1' : '2'
          })
          .then(res => {
            console.log("%c Line:465 🍎 和平营地授权二维码res", "color:#6ec1c2", res);
            if (res.data) {
              this.btnLoading = false;
              this.roleVisible = true
              this.poxiaoHpQrcode = res.data.url

            }
          })
          .catch(err => {
            this.btnLoading = false;
          });
      } else {
        this.$alert("请先填写营地ID！");
      }
    },
    getHpInfo() {
      if (!this.form.f13) {
        this.$alert("请先填写营地ID！");
        return
      }
      this.btnLoading = true;
      infoApi.getHPDatacode({
        yingdi: this.form.f13,
      }).then(res => {
        if (res.code == 200) {
          this.roleVisible = false
          this.btnLoading = false;
          this.form.f11 = res.data.fenseNum
          this.form.f9 = res.data.qiangxie
          this.form.f8 = res.data.shizhuang
          this.form.f7 = res.data.zaiju
          this.showHpCheckbox(res.data)
        }
      })
    },
    //  回显  拼装简介
    showHpCheckbox(res) {
      let data = res
      let str = ''
      let arr
      if (data.skilList) {
        arr = JSON.parse(data.skilList)
        console.log("%c Line:518 🍡 营地数据arr", "color:#4fff4B", arr);
      }
      if (arr && arr.length) {
        arr.forEach(r => {
          str = str + r.name + ' '
        })
      }
      let str2 = `${data.fenseNum}粉装-${data.qiangxie}枪皮-${data.shizhuang}套装-${data.zaiju}载具 `
      this.form.des = (this.form.des || '') + ' ' + str2 + str + ` 营地ID:${this.form.f13} `
      // 回显
      // 回显勾选
      this.attrs.forEach(item => {
        // if (this.form[item.aavName]) {
        if (item.fieldType == "checkbox") {
          item.childAttributes.forEach(t2 => {
            arr.forEach(t3 => {
              if (t3 && (t2.sid==t3.id)) {
                if (this.form[item.aavName + 'rander'].indexOf(t2.id) == -1) {
                  this.form[item.aavName + 'rander'].push(t2.id)
                }
              }
            })
          });
          this.form[item.aavName] = this.form[item.aavName + 'rander'].join(',')
          this.$forceUpdate()
        }
        // }
      });
    },
    /**
         * 
         *  和平精英个性化营地获取 end
         */

    // 获取系统列表
    getSysList() {
      gameDictionaryApi.getChildList({
        gameId: this.form.gameId,
        systemKey: 'system'
      }).then(res => {
        this.sysList = res.rows
      })
    },
    // 编辑时回显 大区 服务器
    reViewArea() {
      this.form.gameType = Number(this.form.gameType)
      if (this.form.gameType == 1) {
        // 端游
        this.getAreaList('', true, this.form.groupId)
      } else {
        this.getSysList()
        this.getYysList(true, this.form.carrierId, this.form.groupId)
      }

    },
    // 系统改变
    sysChange(e) {
      if (e) {
        this.sysList.forEach(i => {
          if (i.id == e) {
            this.form.systemName = i.fieldName
          }
        })
      } else {
        this.form.systemName = ''
      }
    },
    // 服务器改变
    serverChange(e) {
      // console.log("%c Line:353 🍺 e", "color:#7f2b82", e);
      if (e) {
        this.serverList.forEach(i => {
          if (i.id == e) {
            this.form.serverName = i.fieldName
            this.$set(this.form, 'serverId', e)
            this.$forceUpdate()
            // this.form.serverId = e
          }
        })
      } else {
        this.form.serverName = ''
      }
    },
    // 获取运营商列表
    getYysList(flag, yysId, areaId) {
      gameDictionaryApi.getChildList({
        gameId: this.form.gameId,
        systemKey: 'carrier'
      }).then(res => {
        this.carrierList = res.rows
        if (flag) {
          // 回显的时候，获取下一级
          this.getAreaList(yysId, true, areaId)
        }
      })
    },
    // 运营商改变  获取大区列表
    getAreaList(e, flag, areaId) {
      let obj = {
        gameId: this.form.gameId,
        systemKey: 'group'
      }
      if (!flag) {
        // 不是回显的时候，再清除后面的选中
        this.form.groupName = ''
        this.form.groupId = ''
        this.form.serverName = ''
        this.form.serverId = ''
      } else {
        // 回显时，请求服务器列表
        this.getServiceList(areaId, true)
      }

      // 运营商改变 找出选择的运营商的对象
      if (e) {
        this.carrierList.forEach(i => {
          if (i.id == e) {
            obj.systemKey = i.systemKey + 'group'
            this.form.carrierName = i.fieldName
          }
        })
      } else {
        this.form.carrierName = ''
      }
      gameDictionaryApi.getChildList(obj).then(res => {
        this.areaList = res.rows
      })
    },
    // 大区改变  获取服务器列表
    getServiceList(e, flag) {
      if (!flag) {
        // 不是回显的时候，再清除后面的选中
        this.form.serverName = ''
        this.form.serverId = ''
      }

      if (e) {
        gameDictionaryApi.getList({
          parentId: e
        }).then(res => {
          this.serverList = res.rows
        })
        this.areaList.forEach(i => {
          if (i.id == e) {
            this.form.groupName = i.fieldName
          }
        })
      } else {
        this.form.groupName = ''
        this.serverList = []
      }
    },
    // 获取游戏属性列表
    getAttrList() {
      this.loading = true
      gameConfigApi.getGameConfig({ gameId: this.form.gameId }).then(res => {
        this.loading = false
        if (res.code == 200) {
          let attrs = res.rows
          if (attrs.length) {
            attrs.forEach(r => {
              if (r.fieldType == 'checkbox') {
                this.$set(this.form, r.aavName + 'rander', [])
              } else {
                this.$set(this.form, r.aavName, '')
              }
              if (r.isEnable == '0' && r.must == 'true') {
                this.rules[r.aavName] = [
                  {
                    required: true,
                    message: `请输入${r.fieldName}`,
                    trigger: "change"
                  }
                ];
              } else {
                if (this.rules[r.aavName]) {
                  delete this.rules[r.aavName]
                }
              }
            });
          }
          this.attrs = JSON.parse(JSON.stringify(attrs))
        }
      });
    },
    // 多选项改变
    checkboxChange(e, key) {
      // console.log("%c Line:474 🍊 e", "color:#6ec1c2", e);
      if (e && e.length) {
        this.form[key] = e.join(',')
      } else {
        this.form[key] = ''
      }
    },

    // 从一键获取的弹窗返回本弹窗
    // autoGetSubmit(data) {
    //   // 数据回显
    //   // this.form.regional = data.areaName;
    //   // this.form.level = this.form.level ? this.form.level : (data.shiming == 1 ? "有二次" : "包人脸");
    //   // this.form.heroes = data.heroNum;
    //   // this.form.skins = data.skinNum;
    //   // this.form.campId = this.form.campId ? this.form.campId : data.campId;
    //   // this.form.guizuLevel = data.vipLevel;
    //   // this.form.guizufen = this.form.guizufen ? this.form.guizufen : data.nobNum;
    //   // this.form.wuji = this.form.wuji ? this.form.wuji : data.inscriptions;
    //   // this.form.yinji = this.form.yinji ? this.form.yinji : data.yinji;
    //   // this.form.des = data.morInfo;
    //   if (data.detailImg && data.detailImg.length) {
    //     let arr = [];
    //     for (let img of data.detailImg) {
    //       arr.push({
    //         name: "游戏交易后台管理",
    //         url: img
    //       });
    //     }
    //     this.imgFileList = this.imgFileList.concat(arr);
    //     this.imgShowList = this.imgShowList.concat(JSON.parse(JSON.stringify(arr)));
    //   }
    //   if (data.titleImg) {
    //     this.form.titleImg = data.titleImg
    //     this.titleImgList = [{ url: data.titleImg, name: "" }];
    //   }
    // },
    // 重置
    reset() {
      this.form = {};
      this.imgFileList = [];
      this.imgShowList = [];
      this.titleImgList = [];
      this.videoList = [];
      this.newImages = []
      this.attrs = []
    },
    /** 查询详情进行回显 */
    handleUpdate(row) {
      const id = row.id || null;
      // this.wzry = false;
      this.loading = true
      goodsListApi.getGoodsDetail(id).then(response => {
        // console.log("%c Line:435 🍧 response", "color:#b03734", response);
        // 请求自定义字段
        gameConfigApi.getGameConfig({ gameId: response.data.gameId }).then(res => {
          this.loading = false
          if (res.code == 200) {
            let attrs = res.rows
            if (attrs.length) {
              attrs.forEach(r => {
                if (r.fieldType == 'checkbox') {
                  this.$set(response.data, r.aavName + 'rander', response.data[r.aavName] ? response.data[r.aavName].split(',') : [])
                  let arr = []
                  if (response.data[r.aavName + 'rander'] && response.data[r.aavName + 'rander'].length) {
                    response.data[r.aavName + 'rander'].forEach(t => {
                      arr.push(Number(t))
                    })
                  }
                  response.data[r.aavName + 'rander'] = arr
                  console.log('多选', response.data[r.aavName + 'rander'])
                } else if (r.fieldType == 'radio') {
                  this.$set(response.data, r.aavName, response.data[r.aavName] ? Number(response.data[r.aavName]) : '')
                }
                if (r.isEnable == '0' && r.must == 'true') {
                  this.rules[r.aavName] = [
                    {
                      required: true,
                      message: `请输入${r.fieldName}`,
                      trigger: "change"
                    }
                  ];
                } else {
                  if (this.rules[r.aavName]) {
                    delete this.rules[r.aavName]
                  }
                }
              });
            }
            this.attrs = JSON.parse(JSON.stringify(attrs))
            this.form = JSON.parse(JSON.stringify(response.data))
            // console.log("%c Line:476 🍡 response.data", "color:#fca650", response.data);
            this.selectedPhone = this.form.telnote
            this.actived = this.form.gameName
            this.reViewArea()
          }
        });


        if (response.data.urlArr) {
          this.imgFileList = response.data.urlArr;
          this.imgShowList = JSON.parse(JSON.stringify(response.data.urlArr));
        }
        if (response.data.titleImg) {
          this.titleImgList = [{ url: response.data.titleImg, name: "" }];
        }
        let video = {};
        this.videoList = [];
        // this.changeSpecial();
        if (response.data.videoUrl) {
          video.name = response.data.videoName;
          video.url = response.data.videoUrl;
          this.videoList[0] = video;
        }
      });
    },
    // 是否特价
    // changeSpecial() {
    //   if (1 == this.form.accType) {
    //     this.ifSpecial = false;
    //   } else {
    //     this.form.specialPrice = null;
    //   }
    // },
    // 游戏类型改变 初始化
    selectDialogGameType() {
      this.getAttrList()
      // // let gameType = this.form.gameName;
      // // this.getSelectGameInfo(gameType);
      // // this.getCustomFiled(gameType);
      // if (!this.isEdit) {
      //   this.getAttrList()
      // }
      // // this.wzry = false;
      // // if ("王者荣耀" == gameType) {
      // //   this.form.campId = ''
      // //   this.wzry = true;
      // // }
    },

    // 根据简介自动识别多选项
    zidongChange() {
      let arr = []
      let tempArr = []
      if (this.form.des) {
        arr = this.form.des.split(' ')
        tempArr = JSON.parse(JSON.stringify(arr))
        if (arr && arr.length) {
          arr.forEach(r => {
            if (r && r.indexOf(',')) {
              tempArr = tempArr.concat(r.split(','))
            }
          })
        }
        arr = tempArr
      }
      // console.log("%c Line:426 🍎 识别出的选项arr", "color:#465975", arr);
      // 回显勾选
      this.attrs.forEach(item => {
        // if (this.form[item.aavName]) {
        if (item.fieldType == "checkbox") {
          item.childAttributes.forEach(t2 => {
            arr.forEach(t3 => {
              if (t3 && (t2.fieldName.indexOf(t3) > -1)) {
                if (this.form[item.aavName + 'rander'].indexOf(t2.id) == -1) {
                  this.form[item.aavName + 'rander'].push(t2.id)
                }
              }
            })
          });
          this.form[item.aavName] = this.form[item.aavName + 'rander'].join(',')
          this.$forceUpdate()
        }
        // }
      });
    },
    /** 一键生成主图 */
    async makeTitleImg() {
      // 处理多选项，拼接duoxuan详情的LIST
      let list = []
      let img = ''
      let str = ''
      this.attrs.forEach(t => {
        if (t.fieldType == 'checkbox') {
          if (this.form[t.aavName]) {
            str = str + this.form[t.aavName] + ','
          }
        }
      })
      let res = await infoApi.getSelectList({
        ids: str
      })
      list = res.data
      // 生成
      let obj = JSON.parse(JSON.stringify(this.form))
      let list2 = JSON.parse(JSON.stringify(this.attrs))
      img = await makeImgsV3.makeTitleImgYjwj(obj, list, list2)
      return img
    },
    /** 一键生成详情图 */
    async makeDetailImgs() {
      // 处理多选项，拼接duoxuan详情的LIST
      let list = []
      let img = ''
      let str = ''
      this.attrs.forEach(t => {
        if (t.fieldType == 'checkbox') {
          if (this.form[t.aavName]) {
            str = str + this.form[t.aavName] + ','
          }
        }
      })
      let res = await infoApi.getSelectList({
        ids: str
      })
      list = res.data
      // 生成
      img = await makeImgsV3.makeDetailImg(list)
      return img
    },
    // 一键获取首图
    async openGetInfoDialog() {
      this.makeTitleImgBtnLoading = true
      let img = ''
      try {
        img = await this.makeTitleImg()
        this.makeTitleImgBtnLoading = false
      } catch {
        this.makeTitleImgBtnLoading = false
      }
      // 上传生成的base64图片
      let titImg = this.base64ToBlob(img);
      let formData = new FormData();
      formData.append("file", titImg);
      postUpload(formData)
        .then(res => {
          this.form.titleImg = res.msg
          this.titleImgList = [{ url: res.msg, name: "" }];
        })
        .catch(e => { });
    },
    // 一键获取详情图
    async getDetailImgs() {
      this.makeDetailImgBtnLoading = true
      let img = ''
      try {
        img = await this.makeDetailImgs()
        this.makeDetailImgBtnLoading = false
      } catch {
        this.makeDetailImgBtnLoading = false
      }
      // 上传生成的base64图片
      let detailImg = this.base64ToBlob(img);
      let formData = new FormData();
      formData.append("file", detailImg);
      postUpload(formData)
        .then(res => {
          this.imgFileList = [{ url: res.msg, name: "" }];
          this.imgShowList = [{ url: res.msg, name: "" }];
        })
        .catch(e => { });
    },
    // 图片转换
    base64ToBlob(code) {
      let parts = code.split(";base64,");
      let contentType = parts[0].split(":")[1];
      let raw = window.atob(parts[1]);
      let rawLength = raw.length;
      let uInt8Array = new Uint8Array(rawLength);

      for (let i = 0; i < rawLength; ++i) {
        uInt8Array[i] = raw.charCodeAt(i);
      }
      return new Blob([uInt8Array], { type: contentType });
    },
    /**以下是图片上传相关 */
    uploadNumber(file, fileList) {
      //限制图片数量
      this.$modal.msgError("最多只能上传50张图片");
    },

    handleVideoSuccess(res, file) {
      if (res.code == 200) {

        this.form.videoUrl = res.data.filePath;
        this.form.videoName = res.data.fileName;
      }
    },
    handleVideoRemove(response, fileList, file) {
      this.form.videoUrl = "";
      this.form.videoName = "";
    },
    // 压缩图片
    compressImage(file) {

      return new Promise((resolve, reject) => {
        new ImageCompressor(file.file, {
          quality: 0.6,
          checkOrientation: false,
          success(result) {

            resolve(result);
          },
          error(e) {
            reject();
          }
        });
      });
    },
    // 上传图片
    async uploadImgs(file) {
      // console.log("%c Line:466 🍆 压缩前file", "color:#2eafb0", file);
      // 获取压缩后的文件流
      let compreeBolb = await this.compressImage(file);
      // console.log("%c Line:468 🎂 压缩后compreeBolb", "color:#33a5ff", compreeBolb);
      const formData = new FormData();
      formData.append('file', compreeBolb);//压缩后的文件会自动转换成二进制文件流类型
      //上传图片到后台
      try {
        let uploadImg = await postUpload(formData)
        file.data = {
          filePath: uploadImg.msg
        }
        file.code = 200
        return (file)
      }
      catch {
        file.code = 500
        return (file)
      }
    },
    // 详情图片上传成功
    handleUploadSuccess(res, file, fileList) {
      if (res.code == 200) {
        // 取得新上传的文件
        this.newImages = fileList.filter(t => {
          return t.url.indexOf('blob:') > -1
        })
      }
    },
    // 详情图片删除
    handleRemove(response, fileList, file) {
      // console.log("%c Line:495 🍎 response", "color:#4fff4B", response);
      const that = this;
      // 1.获取将要删除图片的临时路径
      const filePath = response.url;
      // 2.找到图片对应的索引值
      this.imgFileList.forEach(function (element, key) {
        if (element.url === filePath) {
          that.imgFileList.splice(key, 1); //回显的图片
        }
      });
      this.newImages.forEach(function (element, key) {
        if (element.url === filePath) {
          that.newImages.splice(key, 1); //新上传的图片
        }
      });
    },
    // 图片预览
    handlePictureCardPreview(file) {
      this.$viewerApi({
        images: [file.url]
      });
    },
    imgPreview(url) {
      this.$viewerApi({
        images: [url]
      });
    },
    // 标题图片移除
    handleAvatarRemove(response, file) {
      this.form.titleImg = "";
      this.titleImgList = [];
    },
    // 标题图片上传成功
    handleAvatarSuccess(res, file) {
      if (res.code == 200) {
        let url = res.data.filePath;
        let name = res.data.fileName;
        let param = {};
        param.url = url;
        param.name = name;
        this.titleImgList.push(param);
        this.form.titleImg = res.data.filePath;
      }
    },

    // handleSelectionChange(val) {
    //   this.checkSuperList = val;
    // },
    // 提交
    submitForm(formName) {
      // if ("3" == this.form) {
      //   this.$modal.msgError("终端数据无法编辑！！！,请联系供货商");
      //   return true;
      // }
      this.$refs["" + formName][0].validate(valid => {
        // this.form.urlArr = this.imgFileList;
        if (valid) {
          // 拼接新上传的图片
          if (this.newImages && this.newImages.length) {
            let newArr = []
            this.newImages.forEach(img => {
              newArr.push({
                name: img.name,
                url: img.response.data.filePath
              })
            })
            this.form.urlArr = this.imgFileList.concat(newArr)
          } else {
            this.form.urlArr = this.imgFileList
          }
      
          if (this.isEdit) {
            // 编辑
            goodsListApi.editGoods(this.form).then(response => {
              this.$modal.msgSuccess("编辑成功");
              this.attrs = []
              this.$refs[formName][0].resetFields();
              this.reset()
              this.dialogVisible = false;
              this.$parent.getList();
            });
          } else {
            goodsListApi.addGoods(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.attrs = []
              this.$refs[formName][0].resetFields();
              this.reset()
              this.dialogVisible = false;
              this.$parent.getList();
            });
          }
        } else {
          this.$alert("请填写完整！");
        }
      });
    },
    close() {
      this.dialogVisible = false;
      this.btnLoading = false
      this.makeTitleImgBtnLoading = false
      this.makeDetailImgBtnLoading = false
    },
    resetForm(formName) {
      this.$refs[formName][0].resetFields();
      this.ruleForm.id = this.info.id;
    }
  }
};
</script>
<style scoped lang="css">
.center {
  text-align: center;
}

.form-box {
  height: calc(100vh - 20vh);
  overflow-y: auto;
  overflow-x: hidden;
}

.form-box>>>.el-input {
  width: 250px;
}

.form-box>>>.lattle-input .el-input {
  width: 170px;
}

.form-box>>>.lattle-input2 .el-input {
  width: 110px;
}

.form-box>>>.big-input .el-input {
  width: 100%;
}

.form-box>>>img {
  width: 100%;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.hiddenupload>>>.el-upload--picture-card {
  display: none;
}

/* .form-box >>> .el-upload{
  text-align: left;
} */
.form-box>>>.el-upload-dragger {
  width: 148px;
  height: 148px;
}

>>>.el-dialog__body {
  padding: 10px;
}

>>>.el-tabs__nav-next,
.el-tabs__nav-prev {
  font-size: 18px;
}

.form-box>>>.el-form-item__content {
  max-width: calc(100% - 120px)
}

.form-box>>>.el-input-number {
  width: 250px;
}

.form-box>>>.el-input-number .el-input__inner {
  text-align: left;
}
.form-box>>>.el-checkbox{
  width: 190px;
  margin: 0;
}
</style>
